package com.zys.background.common.web.base.web;

import com.baomidou.mybatisplus.extension.service.IService;
import com.zys.background.common.entity.Result;
import com.zys.background.common.type.ParamType;
import com.zys.background.common.web.base.entity.BaseEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author zys
 * @since 2022-11-19
 */
@Validated
@Api(tags = "通用操作")
@RequiredArgsConstructor
public class BaseController<S extends IService<E>, E extends BaseEntity> {
  private final S service;

  @GetMapping
  @ApiOperation("查询列表")
  public Result<List<E>> list() {
    return Result.success("", service.list());
  }

  @GetMapping("{id}")
  @ApiOperation("查询指定信息")
  @ApiImplicitParam(name = "id", value = "id", required = true, dataTypeClass = String.class, paramType = ParamType.PATH)
  public Result<E> detail(@PathVariable String id) {
    return Result.success("", service.getById(id));
  }

  @DeleteMapping("{id}")
  @ApiOperation("根据 id 删除信息")
  @ApiImplicitParam(name = "id", value = "id", required = true, dataTypeClass = String.class, paramType = ParamType.PATH)
  public Result<Void> delete(@PathVariable  String id) {
    return Result.judge(service.removeById(id));
  }

  @PostMapping
  @ApiOperation("添加信息")
  @ApiImplicitParam(name = "entity", value = "信息", required = true, dataTypeClass = Object.class, paramType = ParamType.BODY)
  public Result<Void> save(@RequestBody @Valid E entity) {
    return Result.judge(service.save(entity));
  }

  @ApiOperation("修改信息")
  @PutMapping("{id}")
  @ApiImplicitParams({
      @ApiImplicitParam(name = "id", value = "id", required = true, dataTypeClass = String.class, paramType = ParamType.PATH),
      @ApiImplicitParam(name = "entity", value = "信息", required = true, dataTypeClass = Object.class, paramType = ParamType.BODY)
  })
  public Result<Void> update(
      @PathVariable String id,
      @RequestBody @Valid E entity
  ) {
    return Result.judge(service.updateById(entity));
  }
}
